<?php

namespace app\admin\controller\express;

use app\admin\model\express\OrderAddress;
use app\admin\model\express\Subscribe;
use app\admin\model\User;
use app\api\model\PackageAddress;
use app\common\controller\Backend;
use think\Config;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Loader;

/**
 * 订单
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{
    
    /**
     * Order模型对象
     * @var \app\admin\model\express\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\express\Order;
        $this->view->assign("stateList", $this->model->getStateList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("isOpenList", $this->model->getIsOpenList());
        $this->view->assign("isDeliveryList", $this->model->getIsDeliveryList());
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        $batch_id = $this->request->param('ids','');
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $batch_id = $this->request->param('batch_id','');
            $w = [];
            if($batch_id){
                $w['batch_id'] = $batch_id;
            }
            $list = $this->model
                    ->with(['user'])
                    ->where($where)
                    ->where($w)->where('is_now','yes')
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                
                $row->getRelation('user')->visible(['nickname','avatar']);
                $row['service'] = \app\admin\model\express\Service::where('id','in',$row['service_ids'])->select();
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        $this->assignconfig('batch_id',$batch_id);
        return $this->view->fetch();
    }

    /**
     * 添加
     */
//    public function add()
//    {
//        if ($this->request->isPost()) {
//            $params = $this->request->post("row/a");
//            if ($params) {
//                $params = $this->preExcludeFields($params);
//
//                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
//                    $params[$this->dataLimitField] = $this->auth->id;
//                }
//                $result = false;
//                Db::startTrans();
//                try {
//                    //是否采用模型验证
//                    if ($this->modelValidate) {
//                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
//                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
//                        $this->model->validateFailException(true)->validate($validate);
//                    }
//                    $user = User::get($params['user_id']);
//                    if(!$user){
//                        $this->error('该用户不存在');
//                    }
//                    $params['order_no'] = $params['user_id'];
//                    $result = $this->model->allowField(true)->save($params);
//                    Db::commit();
//                } catch (ValidateException $e) {
//                    Db::rollback();
//                    $this->error($e->getMessage());
//                } catch (PDOException $e) {
//                    Db::rollback();
//                    $this->error($e->getMessage());
//                } catch (Exception $e) {
//                    Db::rollback();
//                    $this->error($e->getMessage());
//                }
//                if ($result !== false) {
//                    $subscribe = new Subscribe();
//                    $template_id = Config::get('site.new_order');
//                    $page = 'pages/IndexServer/AddPackage/AddPackage?orderid='.$this->model->id;
//                    $data = [
//                        'character_string6' => [
//                            'value' => $this->model->order_no
//                        ],
//                        'phrase3' => [
//                            'value' => '新包裹入库'
//                        ],
//                        'time5' => [
//                            'value' => date('Y-m-d H:i:s',time())
//                        ],
//                        'thing8' => [
//                            'value' => '运单号:'.$this->model->from_express_no.',去完善'
//                        ]
//                    ];
//                    $subscribe->push($params['user_id'],$template_id,$page,$data);
//                    $this->success();
//                } else {
//                    $this->error(__('No rows were inserted'));
//                }
//            }
//            $this->error(__('Parameter %s can not be empty', ''));
//        }
//        return $this->view->fetch();
//    }
//    /**
//     * 编辑
//     */
//    public function edit($ids = null)
//    {
//        $row = $this->model->get($ids,['goods']);
//        if (!$row) {
//            $this->error(__('No Results were found'));
//        }
//        $row['service'] = \app\admin\model\express\Service::where('id','in',$row['service_ids'])->select();
//        $adminIds = $this->getDataLimitAdminIds();
//        if (is_array($adminIds)) {
//            if (!in_array($row[$this->dataLimitField], $adminIds)) {
//                $this->error(__('You have no permission'));
//            }
//        }
//        if ($this->request->isPost()) {
//            $params = $this->request->post("row/a");
//            if ($params) {
//                $params = $this->preExcludeFields($params);
//                $result = false;
//                Db::startTrans();
//                try {
//                    //是否采用模型验证
//                    if ($this->modelValidate) {
//                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
//                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
//                        $row->validateFailException(true)->validate($validate);
//                    }
//
//                    $result = $row->allowField(true)->save($params);
//                    Db::commit();
//                } catch (ValidateException $e) {
//                    Db::rollback();
//                    $this->error($e->getMessage());
//                } catch (PDOException $e) {
//                    Db::rollback();
//                    $this->error($e->getMessage());
//                } catch (Exception $e) {
//                    Db::rollback();
//                    $this->error($e->getMessage());
//                }
//                if ($result !== false) {
//                    if($params['status'] == 'waitingpay'){
//                        $subscribe = new Subscribe();
//                        $template_id = Config::get('site.new_order');
//                        $page = 'pages/Tobepaid/Tobepaid';
//                        $data = [
//                            'character_string6' => [
//                                'value' => $row['order_no']
//                            ],
//                            'phrase3' => [
//                                'value' => '包裹待支付'
//                            ],
//                            'time5' => [
//                                'value' => date('Y-m-d H:i:s',time())
//                            ],
//                            'thing8' => [
//                                'value' => '有新的包裹待支付,支付后平台可进行发货'
//                            ]
//                        ];
//                        $subscribe->push($row['user_id'],$template_id,$page,$data);
//                    }
//                    $this->success();
//                } else {
//                    $this->error(__('No rows were updated'));
//                }
//            }
//            $this->error(__('Parameter %s can not be empty', ''));
//        }
//        $row['address'] = OrderAddress::where('order_id',$row['id'])->find();
//        $this->view->assign("row", $row);
//        return $this->view->fetch();
//    }


    /**
     * 创建批次并加入批次 && 加入批次
     */
    public function addBatch(){
        if($this->request->isPost()){
            $params = $this->request->post('row/a');
            $ids = explode(',',$params['ids']);
            Db::startTrans();
            try{
                if($params['type'] == 'new'){
                    $count = model('app\admin\model\express\Batch')->whereTime('createtime','today')->count();
                    $batch  = model('app\admin\model\express\Batch')->create([
                        'batch_no' => date('Ymd').'-'.($count + 1),
                        'number' => count($ids)
                    ]);
                    $batch_id = $batch['id'];
                }else{
                    $batch_id = $params['batch_id'];
                }
                $this->model->where('id','in',$ids)->setField('batch_id',$batch_id);
                $number = $this->model->where('batch_id',$batch_id)->count();
                model('app\admin\model\express\Batch')->where('id',$batch_id)->setField('number',$number);
                Db::commit();
            }catch (PDOException $e){
                $this->error($e->getMessage());
            }catch (Exception $e){
                $this->error($e->getMessage());
            }
            $this->success('操作成功');
        }

    }



    /**
     * 打印PDF
     */
    public function print($ids = null){
        Loader::import('tcpdf.tcpdf', EXTEND_PATH);
        // create new PDF document
        $pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

// set document information
        $pdf->SetCreator(PDF_CREATOR);
        $pdf->SetAuthor('Nicola Asuni');
        $pdf->SetTitle(date('Y-m-d').'-'.time());
        $pdf->SetSubject('TCPDF Tutorial');
        $pdf->SetKeywords('TCPDF, PDF, example, test, guide');

// remove default header/footer
        $pdf->setPrintHeader(false);
        $pdf->setPrintFooter(false);

// set default monospaced font
        $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

// set margins
        $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);

// set auto page breaks
        $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

// set image scale factor
        $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);


        // ---------------------------------------------------------

        // set font
        $pdf->SetFont('stsongstdlight', 'B', 26);
        // 查询包裹
        $orderList = model('app\admin\model\express\Order')
            ->with(['goods'])
            ->where('id','in',$ids)
            ->select();
        // 循环包裹插入pdf
        foreach ($orderList as $order){
            $consigneeAddress = OrderAddress::get(['order_id'=>$order['id']]);
            $deliveryAddress = Db::name('express_delivery_address')->find();
            $goodsInfo = [];
            foreach ($order['goods'] as $goods){
                //$goodsInfo[] = $goods['name'].'*'.$goods['number'].'('.bcmul($goods['weight'],$goods['number'],2).$goods['unit'].')';
                $goodsInfo[] = str_replace(' ','',$goods['name'].'*'.$goods['number']);
            }
            $goodsInfoStr = implode(';',$goodsInfo);
            // add a page
            $pdf->AddPage();
            $pdf->setJPEGQuality(75);
            $style = array(
                'position' => 'absolute',
                'align' => 'R',
                'stretch' => true,
                'fitwidth' => true,
                'cellfitalign' => '',
                'border' => false,
                'hpadding' => 'auto',
                'vpadding' => 'auto',
                'fgcolor' => array(0,0,0),
                'bgcolor' => false, //array(255,255,255),
                'text' => true,
                'font' => 'helvetica',
                'fontsize' => 12,
                'stretchtext' => 4
            );
            /*$pdf->Image(ROOT_PATH.'public/assets/img/ems.png', 15, 25, 90, 30, 'PNG', '', '', true, 150, '', false, false, 0, false, false, false);
            $pdf->Image(ROOT_PATH.'public/assets/img/ems.png', 135, 175, 60, 20, 'PNG', '', '', true, 150, '', false, false, 0, false, false, false);
            $pdf->Image(ROOT_PATH.'public/assets/img/check.png', 135, 253, 45, 15, 'PNG', '', '', true, 150, '', false, false, 0, false, false, false);
            $pdf->Image(ROOT_PATH.'public/assets/img/logo.jpg', 155, 52, 32, 32, 'JPG', '', '', true, 150, '', false, false, 0, false, false, false);
            $pdf->write1DBarcode($order['express_no'], 'C128', '100', '', '', 30, 0.9, $style, 'R');
            $pdf->Ln();
            $pdf->Cell(60, 10, '收件人:'.$consigneeAddress['name'], 'T', 0, 'L', 0);
            $pdf->Cell(75, 10, '收件电话:'.$consigneeAddress['mobile'], 'TR', 0, 'L', 0);
            $pdf->Cell(45, 10, '', 'T', 0, 'L', 0);
            $pdf->Ln();
            $pdf->MultiCell(135, 20, '收件地址:'.$consigneeAddress['province'].$consigneeAddress['city'].$consigneeAddress['area'].$consigneeAddress['address'], 'R', 'J', '', 0);
            $pdf->Ln();
            $pdf->Cell(90, 10, '寄件人:'.$deliveryAddress['name'], 'T', 0, 'L', 0);
            $pdf->Cell(90, 10, '寄件电话:'.$deliveryAddress['mobile'], 'T', 0, 'L', 0);
            $pdf->Ln();
            $pdf->MultiCell(180, 15, '寄件地址:'.$deliveryAddress['address'], '', 'J', '', 0);
            $pdf->Ln();
            $pdf->Cell(90, 10, '签收人', 'TR', 0, 'L', 0);
            $pdf->Cell(90, 10, '签收时间', 'T', 0, 'L', 0);
            $pdf->Ln();
            $pdf->Cell(90, 10, '', 'R', 0, 'C', 0);
            $pdf->Cell(45, 10, '', '', 0, 'C', 0);
            $pdf->Cell(15, 10, '年', '', 0, 'C', 0);
            $pdf->Cell(15, 10, '月', '', 0, 'C', 0);
            $pdf->Cell(15, 10, '日', '', 0, 'C', 0);
            $pdf->Ln();
            $pdf->Cell(90, 10, '配货信息:', 'TR', 0, 'L', 0);
            $pdf->Cell(90, 10, '重量:'.($order['delivery_weight'].'Kg'), 'T', 0, 'L', 0);
            $pdf->Ln();
            $pdf->MultiCell(90, 35, $goodsInfoStr, 'R', 'J', '');
            $pdf->Cell(180, 0, '', 'T', 0, 'L', 0);
            $pdf->write1DBarcode($order['express_no'], 'C128', 10, '', '', 30, 0.9, $style, '');
            $pdf->Ln();
            $pdf->Cell(90, 15, '寄件人:'.$deliveryAddress['name'], 'TR', 0, 'L', 0);
            $pdf->Cell(90, 15, '收件人:'.$consigneeAddress['name'], 'T', 0, 'L', 0);
            $pdf->Ln();
            $pdf->Cell(90, 15, '寄件电话:'.$deliveryAddress['mobile'], 'R', 0, 'L', 0);
            $pdf->Cell(90, 15, '收件电话:'.$consigneeAddress['mobile'], '', 0, 'L', 0);
            $pdf->Ln();
            $pdf->MultiCell(90, 20, '寄件地址:'.$deliveryAddress['address'], 'R', 'J', '', 0);
            $pdf->MultiCell(90, 20, '收件地址:'.$consigneeAddress['province'].$consigneeAddress['city'].$consigneeAddress['area'].$consigneeAddress['address'], 'L', 'J', '', 0);
            $pdf->Ln();
            $pdf->Cell(180, 20, '打印日期:'.date('Y-m-d'), 'TB', 0, 'L', 0);*/

            $pdf->Image(ROOT_PATH.'public/assets/img/exlogo.png', 15, 28, 80, 25, 'PNG', '', '', true, 150, '', false, false, 0, false, false, false);

            $pdf->write1DBarcode($order['order_no'], 'C128', '100', '', '', 30, 0.9, $style, 'R');
            $pdf->Ln();
            $pdf->Cell(60, 30, '收件人:'.$consigneeAddress['name'], 'T', 0, 'L', 0);
            $pdf->Cell(75, 30, '电话:'.$consigneeAddress['mobile'], 'T', 0, 'L', 0);
            $pdf->Cell(45, 30, 'ID:'.$order['user_id'], 'T', 0, 'L', 0);
            $pdf->Ln();
            $pdf->MultiCell(135, 30, '地址:'.$consigneeAddress['province'].$consigneeAddress['city'].$consigneeAddress['area'].$consigneeAddress['address'], 'TR', 'L', '', 0);
            $pdf->Cell(45, 10, '秤上实重:', 'T', 0, 'C', 0);
            $pdf->Ln();
            $pdf->SetFont('stsongstdlight', 'B', 40);
            $pdf->MultiCell(135, 20, '', 'R', 'L', '', 0);
            $pdf->Cell(45, 20, $order['delivery_weight'].'Kg', '', 0, 'C', 0);
            $pdf->SetFont('stsongstdlight', 'B', 26);
            $pdf->Ln();
            $pdf->Cell(135, 10, '内件信息:', 'TR', 0, 'L', 0);
            $pdf->Ln();
            $pdf->MultiCell(85, 20, $goodsInfoStr, 'R', 'J', '', 0);
            $pdf->Cell(50, 20, '提货仓代码:', 'TR', 0, 'L', 0);
            $pdf->Cell(45, 20, '', 'T', 0, 'L', 0);
            $pdf->Ln();
            $pdf->cell(85, 20, '', 'R', '', '', 0);
            $pdf->SetFont('stsongstdlight', 'B', 45);
            $pdf->Cell(50, 20, 'TY', 'R', 0, 'C', 0);
            $pdf->SetFont('stsongstdlight', 'B', 26);
            $pdf->Cell(45, 20, '', '', 0, 'L', 0);
            $pdf->Ln();
            $pdf->Cell(30, 5, '集运单号:', 'T', 0, 'L', 0);
            $pdf->Cell(105, 5, '', 'TR', 0, 'L', 0);
            $pdf->Ln();
            $pdf->SetFont('stsongstdlight', 'B', 50);
            $pdf->Cell(20, 10, '', '', 0, 'L', 0);
            $pdf->Cell(115, 10, $order['order_no'], 'R', 0, 'L', 0);

            $pdf->Cell(45, 10, '海', '', 0, 'R', 0);
            $pdf->Ln();
            $pdf->SetFont('stsongstdlight', 'B', 26);

            // ---------------------------------------------------------
        }


        //Close and output PDF document
        $pdf->Output(date('Y-m-d').'-'.time(), 'I');
        exit;
    }

    public function orderaction(){
        if(request()->isPost()){
            $from_express_no = request()->param('row/a');
            $order = Db::name('express_order')->where('from_express_no',$from_express_no['from_express_no'])->find();
            if(empty($order)){
                //1.操作员录入订单
                $this->redirect('userorder',['from_express_no'=>$from_express_no['from_express_no']]);
              //  $this->redirect('addorder',['from_express_no'=>$from_express_no['from_express_no']]);
            }elseif ($order['status']=='created'&&$order['is_forecast']=='no'){
                //2.操作人员录入订单，等待用户完善（完善订单）
                $this->success('等待用户完善订单');
            }elseif ($order['status']=='complete'&&$order['is_forecast']=='no'){
                //3.这个订单,用户已经完善过了（完善订单）
                $this->success('在仓订单，下一步用户确定发货');
            }elseif ($order['status']=='created'&&$order['is_forecast']=='yes'){
                //4.需要在仓确定的订单(预报订单)
                $this->redirect('storeok',['from_express_no'=>$from_express_no['from_express_no']]);
            }elseif ($order['status']=='complete'&&$order['is_forecast']=='yes'){
                //5.已在仓确定(预报订单)
                $this->success('已在仓确定，下一步用户确定发货');
            }

        }elseif (request()->isGet()){
            return $this->view->fetch();
        }
    }

    /**
     * @return string
     * @throws Exception
     */
    public function userorder(){
        if($this->request->isGet()){
            $this->assign('from_express_no',request()->param('from_express_no'));
            return $this->view->fetch();
        }elseif ($this->request->isPost()){
           $user_id =  request()->param('row/a')['user_id'];

            if(empty($user_id)){
                $this->error('用户ID不能为空');
            }
            if(empty(Db::name('user')->where('member_id',$user_id)->count())){
                $this->error('用户ID不对');
            }

           $this->redirect('addorder',request()->param('row/a'));
        }
    }


    /**在仓确定
     * @return string
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException\
     */
    public function storeok(){
        if(request()->isPost()){
            $postdata  = $this->request->param('row/a');
            $shelf_number  = $postdata['shelf_number'];
            $from_express_no = $postdata['from_express_no'];
            $delivery_weight = $postdata['delivery_weight'];
            $express_order = Db::name('express_order')->where('from_express_no',$from_express_no)->find();


            $subscribe = new Subscribe();
            $template_id = 'wxSCZ_IiXMVOSylHCNI7H0amN8OkF31BVCT3oZpyEXo';
            if($express_order['is_now']=='yes'){
                //成生包裹
                $packaage_no = orderOn($express_order['user_id']);
                $packaage_id =  Db::name('express_package')->insertGetId([
                    'package_no'=>$packaage_no,
                    'user_id'=>$express_order['user_id'],
                    'is_delivery'=>1,
                    'status'=>'complete',
                    'createtime'=>time(),
                    'updatetime'=>time(),
                ]);
                $address_id = Db::name('express_order_address')->where('order_id',$express_order['id'])->value('id');
                $address = model('app\api\model\OrderAddress')->get($address_id);
                if (!$address) {
                    $this->error('收货地址不存在');
                }
                $packAddressM = new PackageAddress();
                $packAddress = $packAddressM->get([
                    'package_id' => $packaage_id,
                    'user_id' => $express_order['user_id'],
                ]);
                if ($packAddress) {
                    $packAddressM->allowField(true)->save([
                        'package_id' => $packaage_id,
                        'user_id' => $express_order['user_id'],
                        'name' => $address['name'],
                        'mobile' => $address['mobile'],
                        'province' => $address['province'],
                        'city' => $address['city'],
                        'area' => $address['area'],
                        'address' => $address['address'],
                        'zip_code' => $address['zip_code'],
                        'province_index' => $address['province_index'],
                        'city_index' => $address['city_index'],
                        'area_index' => $address['area_index'],
                    ]);
                } else {
                    $packAddressM = new PackageAddress();$packAddressM->allowField(true)->save([
                        'package_id' => $packaage_id,
                        'user_id' => $express_order['user_id'],
                        'name' => $address['name'],
                        'mobile' => $address['mobile'],
                        'province' => $address['province'],
                        'city' => $address['city'],
                        'area' => $address['area'],
                        'address' => $address['address'],
                        'zip_code' => $address['zip_code'],
                    ]);
                }

                Db::name('express_order')->where('from_express_no',$from_express_no)->update([
                    'package_no'=>$packaage_no,
                    'package_id'=>$packaage_id,
                    'status'=>'complete',
                    'delivery_weight'=>$delivery_weight,
                ]);
                $page = 'pages/Packagequery/Packagequery';

            }else{
                $page = 'pages/IndexServer/warehouse/warehouse';
            }

            //$string = '包裹已入库，重量：'.$weight.'KG，体积重：'.$volume.'KG';
           // $string = '包裹已入库，请立即点击进行包裹预报';
            $string = '包裹已入库';
            $data = [
                'character_string1' => [
                    'value' => $from_express_no
                ],
                'thing3' => [
                    //'value' => '包裹已经完成入库，包裹重量为：'.$weight.'KGs，体积重：'.$volume.'KGs。请点击本条推送完善包裹预报信息，如果有任何问题请联系微信客服:qingau_express01'
                    'value' => $string
                ]
            ];

           // dump($express_order['user_id']);die;
            $subscribe->push($express_order['user_id'], $template_id, $page, $data);

            Db::name('express_order')->where('from_express_no',$from_express_no)->update([
                                'status'=>'complete',
                                'shelf_number'=>$shelf_number,
                "delivery_weight"=>$delivery_weight
         ]);

            $this->success('在仓确定成功，下一步用户发货','orderaction');

        }elseif (request()->isGet()){
            $ids = Db::name('express_order')->where('from_express_no',request()->param('from_express_no'))->value('id');
            $row = $this->model->get($ids,['goods']);
            if (!$row) {
                $this->error(__('No Results were found'));
            }
            $row['service'] = \app\admin\model\express\Service::where('id','in',$row['service_ids'])->select();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                if (!in_array($row[$this->dataLimitField], $adminIds)) {
                    $this->error(__('You have no permission'));
                }
            }
            $row['address'] = OrderAddress::where('order_id',$row['id'])->find();
            if($row['delivery_weight']=='0.00'){
                $row['delivery_weight']='';
            }
            $this->view->assign("row", $row);
            $shelf = Db::name('express_order')->where('user_id',Db::name('express_order')->where('shelf_number','not null')->where('from_express_no',request()->param('from_express_no'))->value('user_id'))->field('from_express_no,shelf_number')->select();
            $this->assign('shelf',$shelf);
            $this->assign('from_express_no',request()->param('from_express_no'));
            return $this->view->fetch();
        }
    }

    /**
     * 待完善录单
     */
    public function addorder(){
        if(request()->isPost()){
            $postdata = request()->param('row/a');
            $user_id = $postdata['user_id'];
            $from_express_no = $postdata['from_express_no'];
            $params['user_id'] = Db::name('user')->where('member_id',$user_id)->value('id');
            $params['from_express_no'] = $from_express_no;
            $params['shelf_number']= $postdata['shelf_number'];
            $params['delivery_weight']= $postdata['delivery_weight'];

            $user = User::get($params['user_id']);
            if (!$user) {
                $this->error('该用户不存在');
            }

            $params['from_express_name'] = '';
            $params['order_no'] = $params['user_id'];

            $order_model = model('app\api\model\Order');
            $result = $order_model->allowField(true)->save($params);

            if ($result !== false) {
                $subscribe = new Subscribe();
                $template_id = 'wxSCZ_IiXMVOSylHCNI7H0amN8OkF31BVCT3oZpyEXo';
                $page = 'pages/IndexServer/AddPackage/AddPackage?form_express='. $order_model->from_express_no."&orderid=".$order_model->id.'&'.'type=complete';
                $string = '包裹已入库，请立即点击进行包裹预报';
                $data = [
                    'character_string1' => [
                        'value' => $order_model->from_express_no
                    ],

                    'thing3' => [
                        'value' => $string
                    ]
                ];

                $subscribe=$subscribe->push($params['user_id'], $template_id, $page, $data);
                $this->success('等待用户完善订单','orderaction');
            } else {
                $this->error(__('No rows were inserted'));
            }


        }elseif (request()->isGet()){
            $this->assign('from_express_no',request()->param('from_express_no'));
            $this->assign('user_id',request()->param('user_id'));
            $this->assign('shelf',Db::name('express_order')->where('user_id',request()->param('user_id'))->where('shelf_number','not null')->field('from_express_no,shelf_number')->select());
            return $this->view->fetch();
        }
    }

    public function  counter(){
        if(request()->isPost()){

        $post =  $this->request->param('row/a');
        $weight=$post['weight'];
        $length=$post['length'];
        $wide=$post['wide'];
        $high=$post['high'];
        $num=$post['num'];


        if(empty($length)){
            $this->error('货品长度不能为空');
        }
        if(empty($wide)){
            $this->error('货品宽度不能为空');
        }
        if(empty($high)){
            $this->error('货品高度不能为空');
        }
        if(empty($num)){
            $this->error('货品数量不能为空');
        }

        $volume_weight = $wide*$high*$length/6000*$num;
        $volume = $wide*$high*$length/1000000;

        $w =0;
        if(!empty($weight)){
            if($volume_weight>=$weight){
                $w = $volume_weight;
            }else{
                $w = $weight;
            }
        }

        if(empty($weight)){
            $w = $volume_weight;
        }


        $this->redirect('counter',[
            'weight'=>$weight,
            'length'=>$length,
            'wide'=>$wide,
            'high'=>$high,
            'num'=>$num,
            'volume'=>$volume,
            'volume_weight'=>round($volume_weight,2),
            'w'=>$w,
        ]);

        }elseif (request()->isGet()){
            // length wide high volume num
            $weight='';
            $length='';
            $wide='';
            $high='';
            $volume='';
            $num='';
            $volume_weight='';
            $w = "";

            $data = request()->param();

            if(isset($data['weight'])){
                $weight=$data['weight'];
            }

            if(isset($data['length'])){
                $length=$data['length'];
            }

            if(isset($data['wide'])){
                $wide=$data['wide'];
            }

            if(isset($data['high'])){
                $high=$data['high'];
            }
            if(isset($data['volume'])){
                $volume=$data['volume'];
            }
            if(isset($data['num'])){
                $num=$data['num'];
            }

            if(isset($data['volume_weight'])){
                $volume_weight=$data['volume_weight'];
            }

            if(isset($data['w'])){
                $w=round($data['w'],2);
            }

            if(empty($w)){
                $list = [];
            }elseif (!empty($w)){
                $list = [];

               $list =  Db::name('express_counter')->where('status','normal')->where('deletetime',NULL)->select();

               foreach ($list as $key=>$value){
                   $list[$key]['price'] = $this->js($w,(float)$value['first_weight'],(float)$value['first_price'],(float)$value['additional_weight_ladder'],(float)$value['additioinal_price']);
               }

            }

        //    dump($list);

            $this->assign('weight',$weight);
            $this->assign('length',$length);
            $this->assign('wide',$wide);
            $this->assign('high',$high);
            $this->assign('volume',$volume);
            $this->assign('num',$num);
            $this->assign('volume_weight',$volume_weight);
            $this->assign('w',$w);
            $this->assign('list',$list);
            return $this->view->fetch();
        }
    }

    public function js($w,$first_weight,$first_price,$additional_weight_ladder,$additioinal_price){
        $price = 0;

        if($w<=$first_weight){

            $price+=$first_price;
        }elseif ($w>=$first_weight){
            $price+=$first_price;
            $price += ceil(($w - $first_weight) / $additional_weight_ladder) * $additioinal_price;
        }
        return round($price,2);
    }


}
